{% extends "前端/template.html" %}

{% block title %}
简单翻译-普通翻译-采用机器翻译、速度较快
{% endblock %}

{% block css %}
<style>
.translate-container {
    background: #fff;
    border-radius: 0.5rem;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
    position: relative;
}

.language-select {
    width: auto;
    min-width: 150px;
}

.translate-textarea {
    min-height: 200px;
    resize: none;
    border: none;
    padding: 1.5rem;
    font-size: 1rem;
    line-height: 1.6;
    color: #566a7f;
    background: transparent;
}

.translate-textarea:focus {
    outline: none;
    box-shadow: none;
}

.translate-textarea::placeholder {
    color: #a1acb8;
}

.translate-footer {
    padding: 1rem 1.5rem;
    border-top: 1px solid rgba(0,0,0,.05);
    background: #f8f9fa;
    border-bottom-left-radius: 0.5rem;
    border-bottom-right-radius: 0.5rem;
}

.translate-result {
    min-height: 200px;
    background: #f8f9fa;
    padding: 1.5rem;
    border-radius: 0.375rem;
    color: #566a7f;
    line-height: 1.6;
    font-size: 1rem;
}

.char-count {
    color: #697a8d;
    font-size: 0.875rem;
    display: flex;
    align-items: center;
}

.char-count.warning {
    color: #ff3e1d;
}

.clear-btn {
    position: absolute;
    top: 1rem;
    right: 1rem;
    color: #697a8d;
    cursor: pointer;
    padding: 0.25rem;
    border-radius: 0.375rem;
    display: none;
}

.clear-btn:hover {
    background: #f5f5f5;
    color: #566a7f;
}

.translate-textarea:not(:placeholder-shown) ~ .clear-btn {
    display: block;
}

.switch-btn {
    cursor: pointer;
    transition: transform 0.3s;
}

.switch-btn:hover {
    transform: rotate(180deg);
}

.translate-input {
    min-height: 200px;
    width: 100%;
    padding: 1.5rem;
    background: transparent;
    border: none;
    outline: none;
    font-size: 1rem;
    line-height: 1.6;
    color: #566a7f;
    white-space: pre-wrap;
    word-break: break-word;
    overflow-y: auto;
    cursor: text;
}

.translate-input:empty:before {
    content: attr(data-placeholder);
    color: #a1acb8;
}

.translate-input:focus {
    outline: none;
}

/* 自定义滚动条样式 */
.translate-input::-webkit-scrollbar {
    width: 6px;
}

.translate-input::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.translate-input::-webkit-scrollbar-thumb {
    background: #d9dee3;
    border-radius: 3px;
}

.translate-input::-webkit-scrollbar-thumb:hover {
    background: #b8bec3;
}

/* 隐藏IE的滚动条 */
.translate-input {
    -ms-overflow-style: none;
}

/* 保持输入区域的最小高度 */
.translate-container {
    min-height: 242px;
    display: flex;
    flex-direction: column;
}

.translate-main {
    flex: 1;
    position: relative;
}
</style>
{% endblock %}

{% block content %}
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <div class="d-flex align-items-center mb-4">
                    <!-- 源语言选择 -->
                    <select class="form-select language-select me-3" id="sourceLanguage">
                        <option value="zh">中文</option>
                        <option value="en">英语</option>
                    </select>
                    
                    <!-- 切换按钮 -->
                    <i class="bx bx-transfer text-primary fs-3 mx-3 switch-btn" id="switchLanguage"></i>
                    
                    <!-- 目标语言选择 -->
                    <select class="form-select language-select" id="targetLanguage">
                        <option value="zh">中文</option>
                        <option value="en" selected>英语</option>
                    </select>
                </div>

                <div class="row">
                    <!-- 输入区域 -->
                    <div class="col-md-6">
                        <div class="translate-container">
                            <div class="translate-main">
                                <div 
                                    class="translate-input" 
                                    id="sourceText" 
                                    contenteditable="true"
                                    data-placeholder="请输入要翻译的文本（最多5000字）"></div>
                                <i class="bx bx-x fs-4 clear-btn" id="clearBtn" title="清空文本"></i>
                            </div>
                            <div class="d-flex justify-content-between translate-footer">
                                <button class="btn btn-primary px-4" id="translateBtn">
                                    <i class="bx bx-transfer-alt me-1"></i>翻译
                                </button>
                                <span class="char-count">
                                    <i class="bx bx-text me-1"></i>
                                    <span id="charCount">0</span>/5000
                                </span>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 翻译结果区域 -->
                    <div class="col-md-6">
                        <div class="translate-container">
                            <div class="translate-result" id="translationResult">
                                翻译结果将在这里显示
                            </div>
                            <div class="d-flex justify-content-end p-3 border-top">
                                <button class="btn btn-outline-primary" id="copyBtn">
                                    <i class="bx bx-copy me-1"></i>复制结果
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const sourceText = document.getElementById('sourceText');
    const charCount = document.getElementById('charCount');
    const switchBtn = document.getElementById('switchLanguage');
    const sourceLanguage = document.getElementById('sourceLanguage');
    const targetLanguage = document.getElementById('targetLanguage');
    const translateBtn = document.getElementById('translateBtn');
    const copyBtn = document.getElementById('copyBtn');
    const translationResult = document.getElementById('translationResult');
    const clearBtn = document.getElementById('clearBtn');
    
    // 字数统计和限制
    sourceText.addEventListener('input', function() {
        const text = this.textContent;
        const length = text.length;
        
        // 更新字数统计
        charCount.textContent = length;
        
        // 字数限制
        if (length > 5000) {
            const selection = window.getSelection();
            const range = selection.getRangeAt(0);
            this.textContent = text.slice(0, 5000);
            
            // 恢复光标位置
            range.setStart(this.firstChild, 5000);
            range.collapse(true);
            selection.removeAllRanges();
            selection.addRange(range);
        }
        
        // 当接近字数限制时添加警告样式
        if (length > 4500) {
            charCount.parentElement.classList.add('warning');
        } else {
            charCount.parentElement.classList.remove('warning');
        }
    });
    
    // 清空按钮功能
    clearBtn.addEventListener('click', function() {
        sourceText.textContent = '';
        charCount.textContent = '0';
        charCount.parentElement.classList.remove('warning');
        translationResult.textContent = '翻译结果将在这里显示';
    });
    
    // 翻译函数
    async function translateText(text, fromLang, toLang) {
        try {
            showLoading('翻译中...');
            
            const response = await axios.get('/api/translate/line1/translate/', {
                params: {
                    text,
                    from_lang: fromLang,
                    to_lang: toLang
                }
            });
            
            if (response.data && response.data.length > 0) {
                const translatedText = response.data
                    .sort((a, b) => a.paraIdx - b.paraIdx)
                    .map(item => item.dst)
                    .join('\n\n');
                
                translationResult.textContent = translatedText;
                showToast('翻译完成', 'success');
            } else {
                translationResult.textContent = '翻译失败，请重试';
                showToast('翻译失败', 'error');
            }
        } catch (error) {
            console.error('翻译失败:', error);
            translationResult.textContent = '翻译服务异常，请稍后重试';
            showToast('翻译服务异常', 'error');
        } finally {
            hideLoading();
        }
    }
    
    // 语言切换
    switchBtn.addEventListener('click', function() {
        const temp = sourceLanguage.value;
        sourceLanguage.value = targetLanguage.value;
        targetLanguage.value = temp;
    });
    
    // 复制文本的兼容性函数
    function copyText(text) {
        // 创建临时文本区域
        const textarea = document.createElement('textarea');
        textarea.value = text;
        textarea.style.position = 'fixed';
        textarea.style.opacity = '0';
        document.body.appendChild(textarea);
        
        // 选择文本
        textarea.select();
        textarea.setSelectionRange(0, 99999);
        
        try {
            // 尝试使用现代API
            if (navigator.clipboard && navigator.clipboard.writeText) {
                return navigator.clipboard.writeText(text);
            }
            // 降级使用document.execCommand
            const successful = document.execCommand('copy');
            if (!successful) throw new Error('复制失败');
            return Promise.resolve();
        } catch (err) {
            return Promise.reject(err);
        } finally {
            // 清理临时元素
            document.body.removeChild(textarea);
        }
    }
    
    // 复制结果
    copyBtn.addEventListener('click', function() {
        const result = document.getElementById('translationResult');
        const textToCopy = result.textContent;
        
        if (textToCopy === '翻译结果将在这里显示') {
            showToast('没有可复制的内容', 'warning');
            return;
        }
        
        copyText(textToCopy)
            .then(() => {
                showToast('复制成功', 'success');
            })
            .catch(() => {
                showToast('复制失败', 'error');
            });
    });
    
    // 翻译按钮点击事件
    translateBtn.addEventListener('click', async function() {
        const text = sourceText.textContent.trim();
        if(!text) {
            showToast('请输入要翻译的文本', 'warning');
            return;
        }
        
        const fromLang = sourceLanguage.value;
        const toLang = targetLanguage.value;
        
        if (fromLang === toLang) {
            showToast('源语言和目标语言不能相同', 'warning');
            return;
        }
        
        // 直接调用翻译API
        await translateText(text, fromLang, toLang);
    });
    
    // 禁止粘贴带格式的文本
    sourceText.addEventListener('paste', function(e) {
        e.preventDefault();
        const text = e.clipboardData.getData('text/plain');
        document.execCommand('insertText', false, text);
    });
});
</script>
{% endblock %}

{% block nav_left %}
{% include "前端/components/左侧导航栏.html" %}
{% endblock %}

{% block NavBar %}
{% include "前端/components/搜索框、个人头像.html" %}
{% endblock %}

{% block footer %}
{% include "前端/components/Footer.html" %}
{% endblock %}